import { onUnmounted, ref, watchEffect } from 'vue'
import { defineStore } from 'pinia'
import { setValue, route, getIndex } from '@/common/utils'
import { getPlaylistRecommend, getPlaylistCategory } from '@/common/http.api'
import { usePlayerStore } from '@/stores/player'

export const usePlaylistStore = defineStore(
  'playlist',
  () => {
    // 获取 usePlayerStore 数据和方法
    const playerStore = usePlayerStore()
    // 加载
    const loading = ref(false)
    // 歌单数据
    const playlist = ref([])
    // 歌单信息
    const playlistInfo = ref({})
    // 获取歌单接口数据
    const getPlaylist = async (mode = 0, type) => {
      // 显示加载
      setValue({ target: loading, value: true })
      // 获取数据
      const res =
        mode === 0
          ? await getPlaylistRecommend()
          : await getPlaylistCategory(type)
      // 隐藏加载
      setValue([
        { target: playlist, value: res },
        { target: loading, value: false },
      ])
    }

    // 点击歌单ID获取对应歌单里面的歌曲数据
    const setSongListByPlaylistId = (playlist) => {
      // 设置歌单值
      setValue({ target: playlistInfo, value: playlist })
      // 跳转页面
      route('/pages/songlist/songlist', {
        id: playlist.id,
      })
    }

    // 监听-添加标识
    const stopWatch = watchEffect(
      () => {
        // 获取歌单喜欢索引
        const curLikeIdx = getIndex(
          playerStore.playerCollect.playlist,
          playlistInfo.value.id
        )
        playlistInfo.value.like = curLikeIdx > -1
      },
      { flush: 'post' } // 在组件渲染之后执行副作用函数
    )

    // 停止侦听器
    onUnmounted(() => stopWatch())

    return {
      playlist,
      playlistInfo,
      loading,
      getPlaylist,
      setSongListByPlaylistId,
    }
  },
  {
    persist: true, // 开启后对 state 的数据读写都将持久化
  }
)
